#ifndef _DEBUG_APP_H_
#define _DEBUG_APP_H_

#include<stdio.h>
#include<time.h>
#include<sys/stat.h>
#include<unistd.h>

#define NONE	0
#define LOG 	1
#define WRN		2
#define ERR 	4
#define DEB     8

#define DBG_MASK	(WRN|LOG|ERR)

#define LOG_PATH	"vpi.log"
#define LOGMAXSIZE	(10*1024*1024) // 10MB

/* printf colour */
#define NONE_C       "\033[m"
#define RED          "\033[0;32;31m"
#define LIGHT_RED    "\033[1;31m"
#define GREEN        "\033[0;32;32m"
#define LIGHT_GREEN  "\033[1;32m"
#define BLUE         "\033[0;32;34m"
#define LIGHT_BLUE   "\033[1;34m"
#define DARY_GRAY    "\033[1;30m"
#define CYAN         "\033[0;36m"
#define LIGHT_CYAN   "\033[1;36m"
#define PURPLE       "\033[0;35m"
#define LIGHT_PURPLE "\033[1;35m"
#define BROWN        "\033[0;33m"
#define YELLOW       "\033[1;33m"
#define LIGHT_GRAY   "\033[0;37m"
#define WHITE        "\033[1;37m"

#define SLOG(level, fmt,args...)	\
	do {	\
		printf("[%s]",#level);printf(fmt,##args); \
	}while(0)


#define PLOG(level, fmt,args...)	\
	do {	\
		printf("[%s]",#level);printf(fmt,##args); \
	}while(0)

#define PRINT_PREFIX(dest, prefix)	\
	do{	\
		time_t iTime;	\
		struct tm *stTime;	\
		iTime = time(&iTime);	\
		stTime = localtime(&iTime);	\
		fprintf(dest, "[%s] [%04d-%02d-%02d %02d:%02d:%02d] [%-15s] [%04d]  ", prefix, \
			stTime->tm_year+1900, stTime->tm_mon+1, stTime->tm_mday, stTime->tm_hour,\
			stTime->tm_min, stTime->tm_sec, __func__, __LINE__);	\
	} while(0)

#define PRINT_FILE(prefix, fmt, args...)	\
	do{	\
		FILE *pfile;	\
		struct stat stStat;	\
		if (!access(LOG_PATH, 0)) { \
			stat(LOG_PATH, &stStat);		\
			if (stStat.st_size > LOGMAXSIZE)	\
				remove(LOG_PATH);		\
		}		\
		pfile = fopen(LOG_PATH, "a");	\
		PRINT_PREFIX(pfile, prefix);	\
		fprintf(pfile, fmt, ##args);	\
		fclose(pfile);	\
	} while(0)

#define PRINT_STDOUT(fmt,args...) \
	do{ \
		PRINT_PREFIX(stdout, "DBG"); \
		printf(fmt,##args); \
	}while(0)

#define DBG(flag, fmt, args...) \
	do{ \
		switch (flag&DBG_MASK) { \
		case ERR: \
			PRINT_FILE("ERR", fmt, ##args); \
			break; \
		case LOG: \
			PRINT_FILE("LOG", fmt, ##args); \
			break; \
		case WRN: \
			PRINT_FILE("WRN", fmt, ##args); \
			break; \
		default: \
			PRINT_STDOUT(fmt,##args); \
			break; \
		}\
	} while(0)

#endif
